#!/usr/bin/python
# -*- coding:utf8-*-
"""
导入okex网ticker数据
每分钟运行一次
"""

import json
import time

import utils

TABLE_OKEX_TRADE_TICKER = 'okex_trade_data_ticker'

MAX_TRI_CNT = 20  # 最大尝试次数


class Exchange_data_import:
    def __init__(self, lis_url, table):
        self.u = utils.CoinTools()
        self.conn = self.u.mysqlconnect()
        self.cur = self.conn.cursor()
        self.lis_url = lis_url
        self.table = table

    def run(self):
        lis = []
        for item in self.lis_url:
            print '======================================'
            print item
            dic = {}
            for try_cnt in xrange(MAX_TRI_CNT):
                try:
                    data = self.u.doGet(item)
                    dic = json.loads(data, encoding='utf8')
                    if dic and dic.has_key('date') and dic.has_key('ticker'):
                        break
                except Exception as e:
                    print e
                    print '重新尝试第' + str(try_cnt + 1) + '次....' + item
                    time.sleep(0.5)
            ticker = dic['ticker']
            symbol = str(item).split('=')[-1]
            ts = self.u.secondts_2_mints(long(dic['date']))
            last = ticker['last']
            buy = ticker['buy']
            sell = ticker['sell']
            high = ticker['high']
            low = ticker['low']
            vol = ticker['vol']
            unit_amount = ticker['unit_amount']
            lis.append((symbol, ts, last, buy, sell, high, low, vol, unit_amount))
            time.sleep(1)
        if lis:
            self.insert(lis)

    def insert(self, lis):
        print lis[0]
        if self.table == TABLE_OKEX_TRADE_TICKER:
            sql = """insert into """ + TABLE_OKEX_TRADE_TICKER + """ (symbol, ts, last, buy, sell, high, low, vol, unit_amount) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)"""
            print sql
            self.cur.executemany(sql, lis)
            self.conn.commit()

    def __del__(self):
        self.conn.commit()
        self.cur.close()
        self.conn.close()


def main():
    tool = utils.CoinTools()
    # zb
    lis = ['btc', 'eth', 'bch', 'ltc', 'neo', 'usdt']
    lis_okex_symbol = ['btc_usd', 'ltc_usd', 'eth_usd', 'etc_usd', 'bch_usd']
    url_okex_rest_api = tool.readini('exchanges_teade_data', 'URL_OKEX_API')
    url_okex_ticker = tool.readini('exchanges_teade_data', 'URL_OKEX_TICKER')
    lis_zb = []
    for item in lis_okex_symbol:
        url = url_okex_rest_api + url_okex_ticker + item
        lis_zb.append(url)
    if lis_zb:
        huobi = Exchange_data_import(lis_zb, TABLE_OKEX_TRADE_TICKER)
        huobi.run()


if __name__ == '__main__':
    main()
